var $layer = layer;
var networkErrorMsg = "网络错误,请刷新重试！";
var systemAbnormalityMsg = "系统异常,请联系管理员！";
var device = null;

var ws = null;
var deviceSerialPort;
var alarmAudio;
var sensorAlarmMap = new Map();

$(document).ready(function() {
	$('#syncModal').on('hide.bs.modal', function() {
		closeWebSocket();
		$("#progressTitle").text("同步进度(0/0)")
		$("#progress_rate").css("width", 0 + "%");
		$("#percent").text(0 + "%");
	});

	// 创建传感器显示div面板
	function createSensorPanel(sensorAddress) {
		// 据据传感器地址查找div是否存在，没有就创建,创建时按设备编号排序创建。
		if ($('#sensor-info-panel>tbody>tr[device-id=' + sensorAddress + ']').length <= 0) {
			if ($('#sensor-info-panel>tbody').children('tr').length > 0) {
				var isAdded = false;
				$('#sensor-info-panel>tbody>tr').each(function() {
					if (parseInt($(this).attr('device-id')) > sensorAddress) {
						$(this).before('<tr device-id=' + sensorAddress + '></tr>');
						isAdded = true;
						return false;
					}
				});
				if (isAdded == false) {
					$('#sensor-info-panel>tbody').append('<tr device-id=' + sensorAddress + '></tr>');
				}
			} else {
				$('#sensor-info-panel>tbody').append('<tr device-id=' + sensorAddress + '></tr>');
			}
		}
		return $('#sensor-info-panel>tbody>tr[device-id=' + sensorAddress + ']');
	}

	alarmAudio = document.getElementById("alarm_audio");
	$("#cb_alarm_audio").change(function() {
		if (!$(this).is(':checked')) {
			if (!alarmAudio.paused) {
				alarmAudio.pause();
			}
		}
	});

	device = new Device({
		deviceId: deviceId,
		onDeviceInfo: function(dev) {
			var date = new Date();
			$('#device-name').html(dev.name);
			$('#device-version').html(dev.version); // 版本
			$('#device-update-time').html('更新时间:' + date.toLocaleString());
		},
		onDeviceState: function(dev) {
			$('#device-voltage').html(dev.batteryVoltage.toFixed(1)); // 设备电量
			$('#device-state').removeClass();
			if (dev.initState == 1) {
				$('#device-state').addClass('green');
			} else if (dev.initState == 0) {
				$('#device-state').addClass('yellow');
			}
		},
		onDeviceOnline: function(devId) {
			$('#device-switch').prop("checked", true);
			$('#device-state').removeClass();
			$('#device-state').addClass('green');
		},
		onDeviceOffline: function(devId) {
			$('#device-switch').prop("checked", false);
			$('#device-state').removeClass();
			$('#device-state').addClass('grey');
		},
		onSensorInfo: function(sensor) {
			console.log(sensor)
			// 创建传感器面板并显示数据
			$sensorPanel = createSensorPanel(sensor.address);
			var date = new Date();
			$('#device-update-time').html('更新时间:' + date.toLocaleString());
			var flag = 'green';
			// 如果没有告警就把面板背景变白
			if(sensor.workState =="Disappear"||sensor.workState =="NotFond"){
				flag = 'grey';
			}else if (sensor.isHighAlarm == false && 					// 是否高报
				sensor.isLowAlarm == false && 				// 是否低报
				sensor.isBatteryUnderVoltage == false && 		// 是否电池欠压
				sensor.isModelException == false) {			// 是否模块异常
				$sensorPanel.removeClass('police');
				var $flag = $($($sensorPanel.children('td').get(0)).children('span').get(0));
				flag = 'green';
				if (sensorAlarmMap.get(sensor.address)) {
					sensorAlarmMap.delete(sensor.address);
				}
			} else if (sensor.isBatteryUnderVoltage) {
				flag = 'electricity';
				if(sensor.address && sensor.address != undefined && sensor.address != 'undefined'){
					sensorAlarmMap.set(sensor.address, new Date().getTime());
				}
			} else {
				flag = 'red';
				if(sensor.address && sensor.address != undefined && sensor.address != 'undefined'){
					sensorAlarmMap.set(sensor.address, new Date().getTime());
				}
			}
			var imagePath = '/images/dw_green.png';
			if (flag == 'green') {
				imagePath = '/images/dw_green.png';
			} else if (flag == 'electricity') {
				imagePath = '/images/dw_yellow.png';
			} else if (flag == 'red') {
				imagePath = '/images/dw_red.png';
			}else if (flag == 'grey') {
				imagePath = '/images/dw_grey.png';
			}
			$sensorPanel.html(
				'<td><span class="' + flag + '"></span></td>' +
				'<td>' + sensor.address + '</td>' +
				'<td>' + sensor.gasName + '</td>' +
				'<td>' + (sensor.gasConcentration==0?sensor.gasConcentration:sensor.gasConcentration.toFixed(1)) + sensor.measurementUnit + '</td>' +
				'<td onclick="moveToSensorPos('+sensor.lon+','+sensor.lat+')"> <img style="float: left;" src="'+imagePath+'">' + (sensor.equName?sensor.equName:"") + '</td>' +
				'<td>' + (sensor.average==0?sensor.average:sensor.average.toFixed(1)) + sensor.measurementUnit+ '</td>'+
				'<td onclick="setESM7Equment(\'' + sensor.equNo + '\',\'' + sensor.address + '\')"><img src="/images/postionSport.png"></img></td>'
			);
			if(!$("#cb_edit_device_pos").is(':checked')){
				addDeviveToMap(sensor, flag);
			}
			
			// 判断是否还有告警的数据
			if (sensorAlarmMap.size >0 ) {
				// 开启告警声音
				if (alarmAudio.paused && $("#cb_alarm_audio").is(':checked')) {
					alarmAudio.play();
				}
			} else {
				if (!alarmAudio.paused) {
					alarmAudio.pause();
				}
			}
		},
		onSensorAlarm: function(sensor) {
			// 使显示传感器的div背景变红
			$sensorPanel = createSensorPanel(sensor.address);
			$sensorPanel.addClass('police');
			var $flag = $($($sensorPanel.children('td').get(0)).children('span').get(0));
			if ($flag.length > 0) {
				if (sensor.isBatteryUnderVoltage) {
					$flag.addClass('electricity');
					$flag.removeClass('green');
					$flag.removeClass('red');
				} else {
					$flag.addClass('red');
					$flag.removeClass('green');
					$flag.removeClass('electricity');
				}
			}

			if(sensor.address && sensor.address != undefined && sensor.address != 'undefined'){
				sensorAlarmMap.set(sensor.address, new Date().getTime());
			}
			
			if (sensorAlarmMap.size > 0) {
				// 开启告警声音
				if (alarmAudio.paused && $("#cb_alarm_audio").is(':checked')) {
					alarmAudio.play();
				}
			}
		},
		onDevicePort: function(data) {
			if (data && data.length > 0) {
				$('#device-port-select-option').html('');
				deviceSerialPort = data;
				for (var index in data) {
					$('#device-port-select-option').append('<li>' + data[index] + '</li>');
				}
				$('#device-port-select-option li').bind('click', function() {
					$('#device-port-select-value').text($(this).text());
					$('#device-port-selTion').hide();
				})
			}
		},
		onCloudPush: function(data) {
			if (data) {
				$('#cloud-push-switch').attr("checked", true);
				//				$('#cloud-push-state').removeClass();
				//				$('#cloud-push-state').addClass('green');
			} else {
				$('#cloud-push-switch').attr("checked", false);
				//				$('#cloud-push-state').removeClass();
				//				$('#cloud-push-state').addClass('grey');
			}
		},
		onSensorOffline: function(data) {
			$sensorPanel = createSensorPanel(data.sensorAddress);
			$sensorPanel.addClass('police');
			var $flag = $($($sensorPanel.children('td').get(0)).children('span').get(0));
			if ($flag.length > 0) {
				$flag.removeClass('red');
				$flag.removeClass('green');
				$flag.removeClass('electricity');
				$flag.addClass('grey');
			}
		}
	});
	// 获取设备端口号
	device.getPorts(function(data) {

	}, function(err) {

	});

	// 获取云端推送状态
	device.getCloudPushState(function(data) {

	}, function(err) {

	});

	$('#device-switch').click(function() {
		if ($(this).is(':checked')) {
			//var port = localStorage.devicePort;			// 选择的端口号
			//var interval = localStorage.timeInterval;// 数据上报的时间间隔

			if (!localStorage.devicePort) {
				$('#device-switch').prop("checked", false);
				$('#device-state').removeClass();
				$('#device-state').addClass('grey');
				alert('请先设置串口后启动！');
				return false;
			}
			var port = localStorage.devicePort;			// 选择的端口号
			var interval = localStorage.timeInterval;  // 数据上报的时间间隔
			$(device.open(port, interval, function(data) {
				console.log('开启设备成功,端口号:' + port + ' 上报间隔:' + interval);
			}, function(err) {
				alert('启动设备异常：' + err);
			}));
		} else {
			$(device.close(function() {
				console.log('停止设备成功.：');
				sensorAlarmMap.clear();
				if (!alarmAudio.paused) {
					alarmAudio.pause();
				}
			}, function(err) {
				alert('停止设备异常：' + err);
			}));
		}
	});

	$('#cloud-push-switch').change(function() {
		if ($(this).is(':checked')) {
			$(device.openCloudPush(function(data) {
				console.log('开启云端推送成功.');
			}, function(err) {
				alert('开启云端推送异常：' + err);
			}));
		} else {
			$(device.closeCloudPush(function() {
				console.log('关闭云端推送成功.');
			}, function(err) {
				alert('关闭云端推送异常：' + err);
			}));
		}
	});

	$('#device-option-button').click(function() {
		if (localStorage.devicePort) {
			$('#device-port-select-value').text(localStorage.devicePort + "(异常)");
		}
		if (deviceSerialPort) {
			for (var index in deviceSerialPort) {
				if (localStorage.devicePort == deviceSerialPort[index]) {
					$('#device-port-select-value').text(localStorage.devicePort);
				}
			}
		}
		if (localStorage.timeInterval) {
			$('#time-interval').val(localStorage.timeInterval);
		}
		$('#device-option-panel').toggle();
		return false;
	});

	$('#device-option-panel-close').click(function() {
		$('#device-option-panel').hide();
	});

	$('#device-option-panel-cancel').click(function() {
		$('#device-option-panel').hide();
	});
	$('#device-port').click(function() {
		$('#device-port-selTion').toggle();
	});
	$('#save-device-port').click(function() {
		var devicePort = $('#device-port-select-value').text();
		if (!deviceSerialPort || deviceSerialPort.length == 0) {
			alert("串口异常！");
			return false;
		}
		if (!devicePort || devicePort == '') {
			alert("请选择串口");
			return false;
		}
		var timeInterval = $('#time-interval').val();
		if (!timeInterval || timeInterval == '') {
			alert("请填写时间间隔");
			return false;
		}
		localStorage.devicePort = devicePort;
		localStorage.timeInterval = timeInterval;
	});
});
function closeRealTimeDiv() {
	$("#tenantUnitDiv").fadeOut();
	$("#realTimeDiv").fadeOut();
	$("#realTimeDiv").animate({
		width: "0px"
	}, {
		speed: "slow"
	});
	$(".history").animate({
		left: "40px"
	}, {
		speed: "slow"
	});
}

function showRealTimeDiv() {
	$("#tenantUnitDiv").fadeOut();
	$("#realTimeDiv").toggle();
	$("#realTimeDiv").animate({
		width: "420px"
	}, {
		speed: "slow"
	});
	$("#realTimeDiv").show();
	$(".history").animate({
		left: "422px"
	}, {
		speed: "slow"
	});
}

function showAfwzDiv() {
	$("#afwzDiv").toggle();
	$("#afwzDiv").animate({
		width: "300px"
	}, {
		speed: "slow"
	});
	getAssetDataFn();
}
function getAssetDataFn() {
	$.ajax({
		type: "post",
		url: "/option/asset/queryAssetDataList",
		data: null,
		dataType: "json",
		headers: {
			"Content-Type": "application/json;charset=utf-8"
		},
		success: function(data) {
			if (data) {
				var html = "";
				if (data.length > 0) {
					for (var i = 0; i < data.length; i++) {
						var no = i + 1;
						html += '<tr >';
						html += '<td>' + no + '</td>';
						html += '<td>' + data[i].smName + '</td>';
						html += '<td>' + data[i].smNum + '</td>';
						html += '<td>' + data[i].smNormalNum + '</td>';
						html += '<td>' + data[i].smAbnormalNum + '</td>';
						html += '<td>' + data[i].smExpireNum + '</td>';
						html += '<td>' + data[i].smUnexpiredNum + '</td>';
						html += '</tr>';
					}
				}
				$("#assetDataTableBoby").empty();
				$("#assetDataTableBoby").append(html);
			}
		},
		error: function(request) {
			layer.msg(networkErrorMsg, {
				time: 2000
			});
		}
	})
}

function closeAfwzDiv() {
	$("#afwzDiv").fadeOut();
	$("#afwzDiv").animate({
		width: "0px"
	}, {
		speed: "slow"
	});
}

function closeHistoryRealTimeDiv() {
	$("#historyRealTimeDiv").fadeOut();
	$("#historyRealTimeDiv").animate({
		width: "0px"
	}, {
		speed: "slow"
	});
}

function showHistoryRealTimeDiv() {
	if($("#historyRealTimeDiv").is(":visible"))return false;
	$("#realTimeDiv").hide();
	$("#historyRealTimeDiv").toggle();
	$("#historyRealTimeDiv").animate({
		width: "100%",
		left:"40px"
	}, {
		speed: "2000"
	});
	$("#gasLiId").addClass("onlike").siblings().removeClass("onlike");
	$("#gasHistoryDataDivId").show();
	$("#gasHistoryChartDivId").hide();
	var loading = layer.load(2);
	$.ajax({
		type: "post",
		url: "/historyData/queryHistoryGasDataDate",
		data: null,
		dataType: "json",
		headers: {
			"Content-Type": "application/json;charset=utf-8"
		},
		success: function(data) {
			layer.close(loading);
			if (data && data.length > 0) {
				$("#historyGasDataStartTime").val(data[0]);
				$("#historyGasDataEndTime").val(data[1]);
			} else {
				$("#historyGasDataStartTime").val(getStartCurrentDay());
				$("#historyGasDataEndTime").val(getEndCurrentDay());
			}
			pageNum = 1;
			pageSize = 10;
			$("#historyGasDataPage").html("");
			$("#historyGasDataPage").show();
			getHistoryGasDataFn();
		},
		error: function(request) {
			layer.msg(networkErrorMsg, {
				time: 2000
			});
		}
	})

}

// 设置设备点坐标
function setESM7Equment(equNo, address) {
	if(!$("#cb_edit_device_pos").is(':checked')){
		layer.confirm('请先勾选编辑位置，勾选后可进行设备位置编辑，编辑成功后请取消勾选，以便更新设备位置。', {
			title: '提示信息',
			btn: ['确定'] //按钮

		});
		return false;
	}
	var params = {};
	params.featureId = "device" + address, params.oid = "device" + address;
	params.equNo = equNo;
	params.catecd = "sensor";
	params.clusterType = 'esm27q';
	params.imagePath = "/mapIcon/mapFixedIcon/qtIcon.png";
	params.isCluster = false;
	params.clusterImagePath = "/mapIcon/iconCluster/qtIcon_c.png";
	params.isSave = true;
	params.name = '设备'+address;// 设备名称
	params.address = address + '';// 设备管道
	params.recordType = 'sensor';
	params.action = "传感器位置";
	addMakerEngine(params);
}

function saveEquipmentPos(equNo, adress, lon, lat,name) {
	var params = {};
	params.equNo = equNo;
	params.equChannel = adress;
	params.equName = name;
	params.equLon = lon;
	params.equLat = lat;
	params.tenantId = tenantId;
	$.ajax({
		type: 'POST',
		url: '/equipment/pos',
		data: JSON.stringify(params),
		dataType: 'JSON',
		headers: {
			"Content-Type": "application/json;charset=utf-8"
		},
		success: function(data) {
			if (data.httpCode == 200) {
				layer.msg("保存成功", {
					time: 1000
				});
			} else {
				/*layer.msg(data.msg, {
					time: 1000
				});*/
				layer.confirm(data.msg, {
					title: '提示信息',
					btn: ['确定'] //按钮
				});
			}
		}
	});
}

function deleteEquipmentPos(featureid,equNo, name) {
	var params = {};
	params.equNo = equNo;
	params.equChannel = name;
	params.tenantId = tenantId;
	$.ajax({
		type: 'DELETE',
		url: '/equipment/pos',
		data: JSON.stringify(params),
		dataType: 'JSON',
		headers: {
			"Content-Type": "application/json;charset=utf-8"
		},
		success: function(data) {
			if (data.httpCode == 200) {
				// layer.msg("删除成功", {time: 1000});
				deleteSensorFeatureNoSyn(featureid);
			} else {
				layer.msg(data.msg, {
					time: 1000
				});
			}
		}
	});
}

function addDeviveToMap(sensor, flag) {
	if (sensor.lon != null && sensor.lat != null && typeof sensor.lon != ''
		&& typeof sensor.lat != '' && sensor.lon != 0 && sensor.lat != 0) {
		var coordinate = ol.proj.transform([sensor.lon, sensor.lat],
			'EPSG:4326', 'EPSG:3857');
		var imagePath = '/images/dingwei-green.png';
		if (flag == 'green') {
			imagePath = '/images/dingwei-green.png';
		} else if (flag == 'electricity') {
			imagePath = '/images/dingwei-yellow.png';
		} else if (flag == 'red') {
			imagePath = '/images/dingwei-red.png';
		}else if (flag == 'grey') {
			imagePath = '/images/dingwei-grey.png';
		}
		var params = {
			"type": "Feature",
			"id": "device" + sensor.address,
			"geometry": {
				"type": "Point",
				"coordinates": [coordinate[0], coordinate[1]]
			},
			"properties": {
				"type": "Point",
				"points": [[coordinate[0], coordinate[1]]],
				"params": {
					"type": "marker",
					"oid": "device" + sensor.address,
					"name": sensor.equName,
					"recordType": "sensor",
					"equNo": sensor.equNo,
					"address":sensor.address,
					"clusterType": "esm27q",
					"catecd": "sensor",
					"imagePath": imagePath,
					"isCluster": false,
					"clusterImagePath": "/mapIcon/iconCluster/qtIcon_c.png",
					"isSave": true,
					"action": "传感器位置",
				},
				"name": sensor.address + '',
				"plotType": "Marker"
			}
		}
		positionSynMark(params);
	}
}

function openSyncModal() {
	openWebSocket();
	$("#syncStartTime").val(getStartCurrentDay());
	$("#syncEndTime").val(getEndCurrentDay());
	$("#syncModal").modal('show');
}
function getStartCurrentDay() {
	var day = new Date();
	day.setTime(day.getTime());
	var s = day.getFullYear() + "-" + initSt((day.getMonth() + 1)) + "-"
		+ initSt(day.getDate()) + " " + initSt((day.getHours() - 1)) + ":"
		+ initSt(day.getMinutes()) + ":" + initSt(day.getSeconds());
	return s;
};

function getEndCurrentDay() {
	var day = new Date();
	day.setTime(day.getTime());
	var s = day.getFullYear() + "-" + initSt((day.getMonth() + 1)) + "-"
		+ initSt(day.getDate()) + " " + initSt(day.getHours()) + ":"
		+ initSt(day.getMinutes()) + ":" + initSt(day.getSeconds());
	return s;
};
function startSync() {
	var startTime = $("#syncStartTime").val();
	var endTime = $("#syncEndTime").val();
	var checkResult = checkDate(startTime, endTime);
	if (checkResult == 1) {
		layer.msg("开始时间不能为空！");
	} else if (checkResult == 2) {
		layer.msg("结束时间不能为空！");
	} else if (checkResult == 3) {
		layer.msg("开始时间不能大于结束时间！");
	} else {
		var params = {};
		params.startTime = startTime;
		params.endTime = endTime;
		$.ajax({
			type: "post",
			url: "/synch",
			data: JSON.stringify(params),
			dataType: "json",
			headers: {
				"Content-Type": "application/json;charset=utf-8"
			},
			success: function(data) {
				console.log(data);
				if (data) {
					if (data.httpCode == 200) {
						layer.msg(data.data);
					} else {
						layer.msg(data.msg, {
							icon: 2,
							time: 2000
						});
					}
				}
			},
			error: function(request) {
				layer.msg("同步数据错误！", {
					icon: 2,
					time: 2000
				});
			}
		});
	}
}

function checkDate(startTime, endTime) {/* 0成功，1开始时间不能为空，2结束时间不能为空，3开始时间不能大于结束时间，4时间间隔不能超过5天 */
	var result = 0;
	if (startTime == null || startTime == "") {
		result = 1;
		return result;
	}
	if (endTime == null || endTime == "") {
		result = 2;
		return result;
	}
	var sTime = new Date(startTime.replace(/-/g, "\/"));
	var eTime = new Date(endTime.replace(/-/g, "\/"));
	if (sTime > eTime) {
		result = 3;
		return result;
	}
	return result;
};

function openWebSocket() {
	var wsUrl = "ws://" + window.location.host + "/websocket/" + userId
		+ "/synch";
	if ("WebSocket" in window) {
		ws = new WebSocket(wsUrl);
		ws.onopen = function(event) {
			console.log('建立连接')
		}
		// 接收到消息的回调方法
		ws.onmessage = function(event) {
			console.log('接收到内容：' + event.data);
			if (event.data == "连接成功") {
				return;
			}
			var obj = JSON.parse(event.data);
			if (obj) {
				if (obj.errMsg != null && obj.errMsg != '') {
					layer.msg("errMsg");
					return;
				}
				$("#progressTitle").text(
					"同步进度(" + obj.send + "/" + obj.total + ")")
				$("#progress_rate").css("width", obj.percent + "%");
				$("#percent").text(obj.percent + "%");
			}
		}
		// 连接发生错误的回调方法
		ws.onerror = function(event) {
			console.log('发生错误')
		}
		// 连接关闭的回调方法
		ws.onclose = function(event) {
			console.log('关闭连接')
		}
	} else {
		// 浏览器不支持 WebSocket
		console.log("您的浏览器不支持 WebSocket!");
	}
}

// 发送消息
function sendMessage(message) {
	ws.send(message);
}

// 关闭连接
function closeWebSocket() {
	ws.close();
}

// 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = function() {
	wx.close();
}
